<template>
  <el-form ref="form" :model="form" label-width="80px">
<el-form-item label="*商品名称">
      <el-input style="width:200px;" v-model="form.goodsName"></el-input>
    </el-form-item>

  <!-- 属性组选择-->
  <el-form-item label="*属性组选择">
    <el-select v-model="form.groupName" @change="getAttrByGroup" placeholder="属性组">
      <el-option v-for="(item,index) in attrGroupList" :label="item.groupName" :value="item.groupName" :key="index">
      </el-option>
    </el-select>
  </el-form-item>

  <el-form-item v-for="(attr,index) in attrList">
    <!-- 固定属性 -->
    <template v-if="attr.attrType==1">
      <span>{{attr.attrName}}（固定属性）</span>
      <el-select v-model="form.attr[index]" :placeholder="attr.attrName" :key="index">
        <el-option v-for="(option,index2) in attr.options" :label="option" :value="option" :key="index2+100">
        </el-option>
      </el-select>
    </template>

    <!-- 复选属性 -->
    <template v-if="attr.attrType==3">
      <span>{{attr.attrName}}(复选属性）</span>
      <el-select v-model="form.attr[index]" multiple :placeholder="attr.attrName">
        <el-option v-for="option,index in attr.options" :key="index" :label="option" :value="option">
        </el-option>
      </el-select>
    </template>

    <!-- 单选属性 -->
    <template v-if="attr.attrType==2">
      <span>{{attr.attrName}}(单选属性）</span>
      <el-select v-model="form.attr[index]" :placeholder="attr.attrName" :key="index">
        <el-option v-for="(option,index2) in attr.options" :label="option" :value="option" :key="index2+100">
        </el-option>
      </el-select>
    </template>

    <!-- 自定义属性 -->
    <template v-if="attr.attrType==4">
      <span>{{attr.attrName}}(自定义属性）</span>
      <el-select v-model="form.attr[index]" multiple :placeholder="attr.attrName">
        <el-option v-for="option,index in attr.options" :key="index" :label="option" :value="option">
        </el-option>
      </el-select>
    </template>
  </el-form-item>

    <!-- 仓库选择-->
    <el-form-item label="*仓库选择">
      <el-select @change="whChange" v-model="form.whCode" placeholder="仓库">
        <el-option v-for="(item,index) in whList" :label="item.whName" :value="item.whCode" :key="index"></el-option>
      </el-select>
    </el-form-item>

    <!-- 门店选择-->
    <el-form-item label="*门店选择">
      <el-select v-model="form.shopCode" placeholder="门店">
        <el-option v-for="(item,index) in shopList" :label="item.shopName" :value="item.shopCode" :key="index">
        </el-option>
      </el-select>
    </el-form-item>

    <el-form-item>
      <el-row :gutter="20">
        <el-col :span="12"><span>是否可租</span>
          <el-switch active-value=1 inactive-value=0 v-model="form.isRentable"></el-switch>
        </el-col>
        <el-col :span="12"><span>是否可售</span>
          <el-switch active-value=1 inactive-value=0 v-model="form.isSalable"></el-switch>
        </el-col>
      </el-row>
    </el-form-item>

    <el-form-item label="*备注">
      <el-input id="goodsDesc" style="width:100%;" type="textarea" v-model="form.goodsDesc"></el-input>
    </el-form-item>

    <el-form-item>
      <el-button @click="fillPicUrl">查看图片</el-button>
      <el-button @click="changePic">修改图片</el-button>
    </el-form-item>

    <el-form-item v-if="showPic">
      <div v-for="(item,index) in fileList" class="block">
          <span class="demonstration">{{item.picType}}</span>
          <el-image :preview-src-list="urlList" :src="item.url"></el-image>
      </div>
    </el-form-item>

    <el-form-item v-if="upPic" lable="图片上传">
      <div>
        <div class="img-list">
          <div class="img-content" v-for="(item,index) in fileList" :key="index">
            <span>{{ item.picType }}</span>
            <el-upload class="avatar-uploader" action="#"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="(file, fileList) => {changeUrl(file, fileList, index)}">
              <img v-if="item.url" :src="item.url" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <!-- <i @click="deleteFile(index)" v-if="item.url" class="addGoodsdeletei el-icon-delete"></i> -->
          </div>
        </div>
      </div>
    </el-form-item>
    <el-button @click="onSubmit()">提交</el-button>
 </el-form>
</template>

<script>
  import Cos from '../../static/cos-js-sdk-v5.min.js'
  export default{
    name:"UpDateGoods",
    data(){
      return{
        form:{
          goodsId: "",
          goodsName: '',
          modifyBy: JSON.parse(localStorage.getItem("loginAccount")).accountId,
          catCode: '',
          subCateCode: "",
          attr: [],
          goodsDesc: '',
          groupName: "",
          brandCode: "",
          whCode: "",
          shopCode: "",
          isRentable: "1",
          isSalable: "1"
        },

        fileList:[],

        finishFlag:false,

        finishFlag2:false,

        inputDate:"",

        goodsData:"",
        attrList:[],
        //属性组查询结果
        attrGroupList: [],

        // 属性查询结果
        attrList: [],

        // 全部大类
        catList: [],
        // 根据大类获取小类
        subCatList: [],

        // 获取仓库列表
        whList: [],

        //模拟仓库对应门店列表
        shopList: [],

        brandList: [],
        urlList:[],
        picTypeList:[],
        cosUrl:"https://stage3-1259815541.cos.ap-chongqing.myqcloud.com/",

        showPic:false,
        upPic:false
      }
    },
    methods:{
      useParentCloseDialog() {
        this.$emit("closeDialog", false)
      },
      getGoodsInfo(){
        this.$http.get("/pawnGoods/findGoodsById",{
          params:{
            goodsId:this.selectGoodsId
          }}).then(resp=>{
            this.goodsData = resp.data.data
            console.log(resp)
            this.form.goodsName =  this.goodsData.goodsName
            this.form.catCode = this.goodsData.catCode
            this.form.shopCode = Number(this.goodsData.shopCode)
            this.form.subCateCode = this.goodsData.subCateCode
            this.form.brandCode = this.goodsData.brandCode
            this.form.whCode = this.goodsData.whCode
            this.form.groupName = this.goodsData.groupName
            this.fileList = JSON.parse(this.goodsData.picUrl)
            this.form.goodsDesc = this.goodsData.goodsDesc
            this.form.goodsId = this.selectGoodsId
          }).then(resp=>{
            this.getBrandById()
          }).then(resp=>{
              //获取所有仓库
              this.getAllWh()
              //根据仓库获取门店
              this.whChange()
              //获取属性组
              this.getAttrByGroup()
              //下载图片
              this.downloadImg()
          })
      },
      getAllCate() {
        this.$http.get("/pawnProductCat/getAllProductCat", {
          params: {}
        }).then(resp => {
          this.catList = resp.data.data.records
        })
        console.log(this.attrList)
      },
      getSubCatByCatId() {
        this.subCatList = []
        this.attrGroupList = []
        this.form.subCateCode = ""
        this.$http.get("/pawnProductCat/getXProductCatByD", {
          params: {
            catCode: this.form.catCode
          }
        }).then(resp => {
          this.subCatList = resp.data.data.records
          console.log(this.subCatList)
        })
        //获取属性
        this.$http.get("/pawnAttrGroup/getAllGroupName", {
          params: {
            catCode: this.form.catCode
          }
        }).then(resp => {
          this.attrGroupList = resp.data.data
        })
        //获取品牌
        this.$http.get("/pawnBrand/getBrandByCatCode", {
          params: {
            catCode: this.form.catCode
          }
        }).then(resp => {
          this.brandList = resp.data.data
        })
      },
      getAttrByGroup() {
        //清除input
        this.attrList = []
        this.form.attr =[]
        this.$http.get("/pawnAttrConf/getConfByGroupName", {
          params: {
            groupName: this.form.groupName
          }
        }).then(resp => {
          this.attrList = resp.data.data
          var _this = this
          for (let key in this.attrList) {
            this.attrList[key].options = JSON.parse(this.attrList[key].options)
            if (this.attrList[key].attrType == 2 && this.attrList[key].attrType == 4) {
              this.form.attr.push([])
            } else {
              this.form.attr.push("")
            }
          }
        }).then(resp=>{
          this.getGoodsOptions()
        })
      },
      getAllWh() {
        this.$http.get("/pawnWarehouse/getAllwh", {
          params: {

          }
        }).then(resp => {
          console.log(resp.data.data)
          this.whList = resp.data.data
        })
      },
      handleSubCateChange() {
        for (let key in this.subCatList) {
          if (this.subCatList[key].catCode == this.form.subCateCode) {
            this.fileList = JSON.parse(this.subCatList[key].evalPicDef)
            for(let key2 in this.fileList){
              this.fileList[key2]['url'] = ""
            }
            console.log(this.fileList)
            return
          }
        }
      },
      whChange() {
        // 获取仓库对应门店
        this.$http.get("/pawnShopWhRel/getShopByWhCode", {
          params: {
            whCode: this.form.whCode,
          }
        }).then(resp => {
          this.shopList = resp.data.data
        })
      },
      getBrandById(){
        //获取品牌
        this.$http.get("/pawnBrand/getBrandByCatCode", {
          params: {
            catCode: this.form.catCode
          }
        }).then(resp=>{
          this.brandList = resp.data.data
        })
      },
      getShopByShopCode(){
        //获取门店
        this.$http.get("/pawnShop/getShopById",{
          params:{
            shopCode:this.form.shopCode
          }
        }).then(resp=>{
          this.shopList = resp.data.data
        })
      },
      getGoodsOptions(){
        this.$http.get("/pawnGoodsAttrRel/getAttrByGoodsId",{
          params:{
            goodsId : this.selectGoodsId
          }
        }).then(resp=>{
          // console.log(this.form.attr)
          // console.log(resp.data.data)
          // console.log(this.form.attr.length)
          for(let i=0;i<this.form.attr.length;i++){
            if(resp.data.data[i].attrValue.charAt(0)=="["){
              this.form.attr[i]=JSON.parse(resp.data.data[i].attrValue)
            }
            else{
              this.form.attr[i] = resp.data.data[i].attrValue
            }
          }
          console.log(this.form.attr)
          this.finishFlag = true
        })
      },
      downloadImg(){
        var cos = new Cos({
            SecretId: 'AKIDjHYZJmyzjDQN3SaR1LOAgwub1C6k6C1a',
            SecretKey: 'JOEm33oHUQ6JFuJQGp79uObYEdldEZcO',
        });
        var _this = this

        for(let i = 0;i<this.fileList.length;i++){
          var key = this.fileList[i].picUrl
          var picType = this.fileList[i].pictype
          cos.getObject({
              Bucket: 'stage3-1259815541', /* 填入您自己的存储桶，必须字段 */
              Region: 'ap-chongqing',  /* 存储桶所在地域，例如ap-beijing，必须字段 */
              Key: key,  /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
              DataType: 'blob'
          }, function(err, data) {
              var blobUrl = URL.createObjectURL(data.Body)
              _this.urlList.push(blobUrl)
              _this.picTypeList.push(i)
          })
        }

        for(var k = 0;k<this.fileList.length;k++){
          this.fileList[k].url= this.urlList[k]
        }

        this.finishFlag2 = true

        // this.$http.get("")
      },
      test(){
        console.log(this.fileList)
      },
      fillPicUrl(){
        this.upPic=false
        console.log(this.picTypeList)
        for(var i = 0;i<this.fileList.length;i++){
          this.fileList[i].url= this.urlList[i]
        }
        this.form.isSalable = "0"
        this.form.isSalable = "1"
        this.showPic = true
        console.log(this.fileList)
      },
      changePic(){
        this.fillPicUrl()
        this.showPic=false
        this.upPic=true
      },
      changeUrl(file, fileList, index) {
        console.log(fileList)
        const isJPG = (file.raw.type === 'image/jpeg' || file.raw.type === 'image/png');
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
          return
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
          return
        }

        var blobUrl = URL.createObjectURL(file.raw);
        this.fileList[index].url = blobUrl
        console.log(this.fileList)
        this.form.isRentable = "0"
        this.form.isRentable = "1"
      },
      deleteFile(index){
        this.fileList[index].url = ""
        this.form.isRentable = "0"
        this.form.isRentable = "1"
        console.log(this.fileList)
      },
      onSubmit() {
        // 检查必选数据是否都有（必选文件）
        console.log(this.form)
        for (let key in this.form) {
          if (this.form[key] == "" | this.form[key].length == 0) {
            alert("*必填数据不能为空")
            return
          }
        }
        for (let key in this.fileList) {
          if (this.fileList[key].url == "" && this.fileList[key].flat == 1) {
            alert("*必上传图片不能为空")
            return
          }
        }

        console.log(this.attrList)
        var newFormAttr = JSON.parse(JSON.stringify(this.attrList))
        for(let i =0;i<this.form.attr.length;i++){
          newFormAttr[i].options = this.form.attr[i]
        }
        console.log(newFormAttr)
        this.form.attr = JSON.stringify(newFormAttr)
        var up_file_dom = document.getElementsByClassName("el-upload__input")
        console.log(up_file_dom.length)
        let data = new FormData();
        for (let i = 0; i < up_file_dom.length; i++) {
          var file = up_file_dom[i].files[0]
          // 由于file对象 pictype 只有getter
          var newfile = new File([file], this.fileList[i].picType, {
            type: "image/jpeg"
          });
          data.append("file", newfile)
        }

        for (let key in this.form) {
          data.append(key, this.form[key])
        }

        console.log(data)
        if(up_file_dom.length>0){
          this.$http({
            method: 'post',
            url: "http://localhost:8888/pawnGoods/updateGoods",
            hearders: {
              'Content-Type': 'multipart/form-data;charset=UTF-8'
            },
            data: data
          }).then(resp => {
            this.useParentCloseDialog()
          })
        }
        else{
          this.$http({
            method: 'post',
            url: "http://localhost:8888/pawnGoods/updateGoodsNoFile",
            hearders: {
              'Content-Type': 'multipart/form-data;charset=UTF-8'
            },
            data: data
          }).then(resp => {
            this.useParentCloseDialog()
          })
        }

      },
    },
    created() {
      this.getGoodsInfo()
    },
    props: ['updateGoodsDialogVisible','selectGoodsId'],
    watch:{
      "form.CatCode":function(){
        //获取属性
        this.$http.get("/pawnAttrGroup/getAllGroupName", {
          params: {
            catCode: this.form.catCode
          }
        }).then(resp => {
          this.attrGroupList = resp.data.data
        })
      },
      "finishFlag":function(){
        this.form.isSalable = "0"
        this.form.isSalable = "1"
      },
      // "finishFlag2":function(){
      //   this.fillPicUrl()
      // }
    }
  }
</script>

<style>
    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .addGoodsdeletei{
      cursor: pointer;
    }
</style>
